package com.atguigu.gulimall.product.service.impl;

import com.alibaba.fastjson.TypeReference;
import com.atguigu.common.to_and_vo.SkuHasStockVo;
import com.atguigu.common.utils.R;
import com.atguigu.gulimall.product.config.MyThreadConfig;
import com.atguigu.gulimall.product.entity.SkuImagesEntity;
import com.atguigu.gulimall.product.entity.SpuInfoDescEntity;
import com.atguigu.gulimall.product.feign.WareFeignService;
import com.atguigu.gulimall.product.service.*;
import com.atguigu.gulimall.product.vo.ItemSaleAttrsVo;
import com.atguigu.gulimall.product.vo.SkuItemAttrGroupVo;
import com.atguigu.gulimall.product.vo.SkuItemVo;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ThreadPoolExecutor;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.atguigu.common.utils.PageUtils;
import com.atguigu.common.utils.Query;

import com.atguigu.gulimall.product.dao.SkuInfoDao;
import com.atguigu.gulimall.product.entity.SkuInfoEntity;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;


@Service("skuInfoService")
public class SkuInfoServiceImpl extends ServiceImpl<SkuInfoDao, SkuInfoEntity> implements SkuInfoService {

    //注入线程池
    @Resource
    private ThreadPoolExecutor threadPoolExecutor;

    @Resource
    private WareFeignService wareFeignService;


    @Resource
    private SkuSaleAttrValueService skuSaleAttrValueService;

    @Resource
    private SkuImagesService skuImagesService;

    @Resource
    private SpuInfoDescService spuInfoDescService;

    @Resource
    private AttrGroupService attrGroupService;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<SkuInfoEntity> page = this.page(
                new Query<SkuInfoEntity>().getPage(params),
                new QueryWrapper<SkuInfoEntity>()
        );

        return new PageUtils(page);
    }

    @Override
    public void saveSkuInfo(SkuInfoEntity skuInfoEntity) {
        baseMapper.insert(skuInfoEntity);
    }

    /**
     * sku检索
     * key:
     * catelogId: 0
     * brandId: 0
     * min: 0
     * max: 0
     * @param params
     * @return
     */
    @Override
    public PageUtils queryPageByCondition(Map<String, Object> params) {
        QueryWrapper<SkuInfoEntity> wrapper = new QueryWrapper<>();
        String key = (String)params.get("key");
        if(!StringUtils.isEmpty(key)){
            wrapper.and((w -> {
                w.eq("sku_id",key).or().like("sku_name",key);
            }));
        }
        String brandId = (String)params.get("brandId");
        if(!StringUtils.isEmpty(brandId) && !"0".equalsIgnoreCase(brandId)){
            wrapper.eq("brand_id",brandId);
        }

        String catelogId = (String)params.get("catelogId");
        if(!StringUtils.isEmpty(catelogId)  && !"0".equalsIgnoreCase(catelogId)){
            wrapper.eq("catalog_id",catelogId);
        }

        String min = (String)params.get("min");
        if(!StringUtils.isEmpty(min)){
            wrapper.ge("price",min);
        }
        String max = (String)params.get("max");
        if(!StringUtils.isEmpty(max)){
            try {
                BigDecimal bigDecimal = new BigDecimal(max);
                if(bigDecimal.compareTo(new BigDecimal("0"))==1){
                    wrapper.le("price",max);
                }
            }catch (Exception e){
            }
        }

        IPage<SkuInfoEntity> page = this.page(
                new Query<SkuInfoEntity>().getPage(params),
                wrapper
        );

        return new PageUtils(page);
    }

    @Override
    public List<SkuInfoEntity> getskuBySpuId(Long spuId) {
        List<SkuInfoEntity> skuInfoEntities = baseMapper.selectList(new QueryWrapper<SkuInfoEntity>().eq("spu_id", spuId));
        return skuInfoEntities;
    }

    @Override
    public SkuItemVo item(Long skuId) throws ExecutionException, InterruptedException {
        SkuItemVo skuItemVo = new SkuItemVo();

        //异步编排
        CompletableFuture<SkuInfoEntity> infoFuture = CompletableFuture.supplyAsync(() -> {
            //1.sku基本信息的获取 pms_sku_info
            SkuInfoEntity byId = getById(skuId);
            skuItemVo.setInfo(byId);
            return byId;
        }, threadPoolExecutor);

        CompletableFuture<Void> imageFuture = CompletableFuture.runAsync(() -> {
            //2，sku图片的信息 pms_spu_images
            List<SkuImagesEntity> skuImagesEntities = skuImagesService.getImagesBySkuId(skuId);
            skuItemVo.setSkuImagesEntities(skuImagesEntities);
        }, threadPoolExecutor);

        CompletableFuture<Void> saleAttrFuture = infoFuture.thenAcceptAsync((result)->{
            //3. 获取当前sku对应的spu的所有属性的组合，即获取到所有的sku信息
            List<ItemSaleAttrsVo> itemSaleAttrsVos = skuSaleAttrValueService.getSaleAttrsBySpuId(result.getSpuId());
            skuItemVo.setSaleAttrsVos(itemSaleAttrsVos);
        },threadPoolExecutor);

        CompletableFuture<Void> descFuture = infoFuture.thenAcceptAsync((result)->{
            //4.获取spu的介绍   SpuInfoDescEntity     pms_spu_info_desc
            SpuInfoDescEntity entity = spuInfoDescService.getById(result.getSpuId());
            skuItemVo.setSpuInfoDescEntity(entity);
        },threadPoolExecutor);


        CompletableFuture<Void> baseAttrFuture = infoFuture.thenAcceptAsync((result)->{
            //5.获取spu的规格参数的信息
            List<SkuItemAttrGroupVo> attrGroupVos = attrGroupService.getAttrGroupWithAttrsBySpuId(result.getSpuId(),result.getCatalogId());
            skuItemVo.setGroupAttrs(attrGroupVos);

        },threadPoolExecutor);


        ArrayList<Long> list = new ArrayList<>();
        list.add(skuId);
        //查询该sku是否有库存
        R skusStock = wareFeignService.getSkusStock(list);
        if(skusStock.getCode() == 0){
            List<SkuHasStockVo> data = skusStock.getData("data", new TypeReference<List<SkuHasStockVo>>() {
            });
            SkuHasStockVo skuHasStockVo = data.get(0);
            skuItemVo.setHasStock(skuHasStockVo.getHasStock());
        }


        //等待所有任务都完成
            CompletableFuture.allOf(imageFuture,saleAttrFuture,descFuture,baseAttrFuture).get();

        return skuItemVo;



    }

}